var util = {

	plus: false,
	
	toast: true,

	// 页面初始化
	pageInit: function(callback){
		mui.plusReady(function() {
			callback.call();
		});

		// 如果发现是浏览器则立即跳转
		var href = location.href;
		if (href.indexOf('http') > -1) {
			callback.call();
		};
	},

	// loading
	loading: function(type, title){
		if (this.plus) {
			if (!type || type == 'open') {
				plus.nativeUI.showWaiting(title)
			} else {
				plus.nativeUI.closeWaiting();
			} 
		};
	},

	// 确认提示框
	confirm: function(text, callback){
		if (this.puls) {
			plus.nativeUI.confirm(text, function(e){
		    callback.call();
	        }, "nativeUI", ["确认","取消"] );
		} else {
			if (confirm(text)) {
				callback.call();
			};
		}
	},

	// 自动消失提示
	alert: function(text){
		var self = this;
		if (this.plus) {
			if (this.toast) {
				this.toast = false;
				plus.nativeUI.toast(text);
				setTimeout(function(){ self.toast = true;}, 2000);
			};
		} else {
			alert(text);
		}
	},

	// 打开新页面
	open: function(url){
		var self = this;
		if (this.plus) {
	        var view = mui.preload({url: url});
	        var ps = setInterval(function(){
	          if (view) {
	            plus.webview.show(view, 'pop-in');
	            window.clearInterval(ps);
	          }
	        }, 100)
	    } else {
	        location.href = url;
	    }
	},

	push: function(content){
		if (this.plus) {
			plus.push.createMessage(content);
		};
	},

	// 两次返回键退出应用
	quit: function(){
		mui.back = function() {
			//首次按键，提示‘再按一次退出应用’
			if (!first) {
				first = new Date().getTime();
				mui.toast('再按一次退出应用'); 
				setTimeout(function() {
					first = null;
				}, 1000);
			} else {
				if (new Date().getTime() - first < 1000) {
					plus.runtime.quit();
				}
			} 
		};
	},

	// 本地存储
	storage: function(key, value){
		var storage = localStorage;
		if (this.plus) storage = plus.storage;
		
		if (value) storage.setItem(key, value);
		if (value == 'null') storage.setItem(key, '');
		else return storage.getItem(key); 
	},

	getDateTime: function(date){
		var d = new Date(parseInt(date));
		var ds = d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate();
		return new Date(ds).getTime();
	},

	formatTime: function(time){
		var date = new Date(time);
		var text = date.getHours() + ":" + date.getMinutes();
		return text;
	},

	formatDate: function(time){
		if(!time) return "老舍";
		var date = new Date(parseInt(time));
		var text = (date.getMonth()+1) + "月" + date.getDate()+'日';
		return text;
	}

}

mui.plusReady(function() {
	util.plus = true;
});

$(function() {
    FastClick.attach(document.body);
});

// 模板引擎扩展
if (template) {

	// 日报发送时间
	template.helper('sendTime', function (time) {
		return util.formatTime(time);
	});

	// 日报发送日期
	template.helper('sentdate', function (time) {
		return util.formatDate(time);
	});
};